import os
#import os.path
#import glob
import logging
#import sys
#import re
#import fileinput
from os.path import exists, split
from forest.registry import register_tool
from forest.api import Tool

logger = logging.getLogger('tools.files.write')

@register_tool('files.write')
def write(fname, data, mode = 'w', perms = None):
    logger.info('Write to: %s' , fname)
    basedir = split(fname)[0]
    if basedir and not exists(basedir):
        os.makedirs(basedir)

    f = open(fname, mode)
    f.write(data)
    f.close()
    if perms is not None:
        os.chmod(fname, perms)

    Tool.SIGNAL_TOOL_FINISH(write, level=logging.INFO, message='Write to: %s' % (fname))

